<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 *
 * @author vostro
 *
 */
class MyUpload {

	/**
	 * @author DatDM
	 * @param string optional $filename
	 * @param string optional $allowed_types
	 * @param int optional $max_size
	 * @return error => string, ok => array data
	 */
	public function doUpload($filename = '', $allowed_types = 'gif|jpg|png', $max_size = '10000') {
		$config['upload_path'] = "public/uploads/";
		$config['allowed_types'] = $allowed_types;
		$config['max_size']	= $max_size; // in kilobytes
		$config['encrypt_name'] = true;
		$config['overwrite'] = true;
		if($filename == '') {
			$config['file_name'] = time();
		} elseif($filename != 0) {
			$config['file_name'] = $filename;
		}

		$CI =& get_instance();
		$CI->load->library('upload', $config);

		if ( ! $CI->upload->do_upload()) {
			return $CI->upload->display_errors(); // string
		}

		return  $CI->upload->data(); // array
		/*
		 *
		Array
		(
				[file_name] => php.jpg
				[file_type] => image/jpeg
				[file_path] => E:/Work/PHP/Webserver/xampp/htdocs/projects/freetime/template_codeigniter213/public/uploads/
				[full_path] => E:/Work/PHP/Webserver/xampp/htdocs/projects/freetime/template_codeigniter213/public/uploads/php.jpg
				[raw_name] => php
				[orig_name] => php.jpg
				[client_name] => php.jpg
				[file_ext] => .jpg
				[file_size] => 4.98
				[is_image] => 1
				[image_width] => 238
				[image_height] => 180
				[image_type] => jpeg
				[image_size_str] => width="238" height="180"
		)
		* */

	}

	public function resizeImage($full_path, $number = 1, $width = 188, $height = 188) {
		$config['image_library'] = 'gd2'; // GD, GD2, ImageMagick, NetPBM
		$config['source_image']	= $full_path;
		$config['create_thumb'] = TRUE;
		$config['maintain_ratio'] = TRUE;
		$config['width']	 = $width;
		$config['height']	= $height;
		$config['thumb_marker'] = '_thumb_' . $number ;
		//$config['new_image'] = uniqid(true) . $file_ext;

		$CI =& get_instance();

		$CI->load->library('image_lib');

		$CI->image_lib->initialize($config);

		if ( ! $CI->image_lib->resize())
		{
			return $CI->image_lib->display_errors();
		}
		return true;
	}

	public function deleteFile($filename) {
		$fn = "public/uploads/" . $filename; // file_name
		if(is_file($fn)) {
			return unlink($fn);
		}
		return false;
	}
}